package com.my.study.config;

import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ES客户端配置
 *
 * @author: yidujun
 * @create: 2021/07/21 14:41
 */
@Configuration
public class RestESConfig {

    private final ElasticSearchConfig elasticSearchConfig;

    public RestESConfig(ElasticSearchConfig elasticSearchConfig) {
        this.elasticSearchConfig = elasticSearchConfig;
    }

    /**
     * 创建RestHighLevelClient
     *
     * @return {@link RestHighLevelClient}
     * @see CredentialsProvider
     * @see HttpHost
     * @see RestClient
     * @see RestClientBuilder
     */
    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
//        credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        String[] hosts = elasticSearchConfig.getServer().split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length + 1];
        for (int i = 0; i < hosts.length; i++) {
            httpHosts[i] = new HttpHost(hosts[i], elasticSearchConfig.getPort());
        }

        RestClientBuilder restClientBuilder = RestClient
                .builder(httpHosts)
                .setHttpClientConfigCallback(httpAsyncClientBuilder ->
                        httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

        return new RestHighLevelClient(restClientBuilder);
    }
}
